import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter({"/stu", "/student.jsp", "/addStudent", "/addStudent.jsp", "/editStudent", "/editStudent.jsp", "/deleteStudent"})
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        String username = (String) session.getAttribute("username");

        if (username != null) {
            //登录
            filterChain.doFilter(servletRequest, servletResponse); //放行
        } else {
            //未登录
            servletRequest.setAttribute("msg", "请先登录！");
            servletRequest.getRequestDispatcher("Login.jsp").forward(servletRequest, servletResponse);
        }
    }
        @Override
        public void destroy() {

        }
}